package top.oylan.manager.tools.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.oylan.manager.tools.AuthShiroRealm;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by A on 2019/2/11.
 */
@Configuration
public class ShiroConfig {

    @Bean("hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式为MD5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        credentialsMatcher.setHashIterations(12);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    @Bean
    ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/static/**","anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/admin/sign","anon");
        filterMap.put("/admin/menus","anon");
        filterMap.put("/admin/logout","logout");
        filterMap.put("/admin/**","authc");
        filterFactoryBean.setLoginUrl("/admin/login");

        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return filterFactoryBean;
    }

    @Bean(name="securityManager")
    DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("shiroRealm") AuthShiroRealm shiroRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(shiroRealm);
        return defaultWebSecurityManager;
    }

    @Bean(name="shiroRealm")
    AuthShiroRealm getAuthShiroRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher){
        AuthShiroRealm realm = new AuthShiroRealm();
        realm.setCredentialsMatcher(matcher);
        return realm;
    }

    @Bean  // 提供thymeleaf 模板shiro自定义标签的支持
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}
